package com.wd.tw.websocket.client;

import com.wd.tw.config.AppConfig;
import com.wd.tw.service.EventService;
import com.wd.tw.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @className: CustomerClientService
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2025/1/24
 **/
@Service
@Slf4j
public class CustomerClientService {

    @Resource
    AppConfig appConfig;

    @Resource
    TokenService tokenService;

    @Resource
    EventService eventService;

    private CustomizedWebSocketClient socketClient;


    public void connectServer() {

        log.info("CusSocketClient:" + socketClient);
        String token = tokenService.getToken();
        if (token == null) {
            log.info("websocket connect box token is null!");
            return;
        }
        if (socketClient != null) {
            if (socketClient.isOpen()) {
                return;
            }
        }
        initConnection();

    }

    public void reConnect() {
        try {
            log.info("CloseWebSocketClient");
            socketClient.close();
        } catch (Exception e) {
            log.error("CloseException:" + e.getMessage());
        }
        initConnection();
    }

    private void initConnection() {

        String webSocketUri = appConfig.getWsUrl() + "/open?token=" + tokenService.getToken();

        URI uri = null;
        try {
            uri = new URI(webSocketUri);
        } catch (
                URISyntaxException e) {
            e.printStackTrace();
        }
        log.info("begin to connect websocket:" + webSocketUri);
        socketClient = new CustomizedWebSocketClient(uri, eventService, "Edge_Box_01");
        log.info("socketId:" + socketClient);

        // 设置连接丢失的超时时间为60秒
        socketClient.setConnectionLostTimeout(60 * 60 * 24 * 7);

        //启动时创建客户端连接
        socketClient.connect();

    }
}
